//
//  HNSH_ShopApplyInfoView.m
//  HNSH_SingleProject
//
//  Created by 李宇廷 on 2023/3/4.
//

#import "HNSH_ShopApplyInfoView.h"

//cell
#import "HNSH_ShopApplyInputCell.h"
#import "HNSH_ShopApplySelectCell.h"
#import "HNSH_ShopApplyUpLoadCell.h"

//toor
#import "HNSH_AuthTool.h"
#import "HNSH_MineImageAlert.h"


@interface HNSH_ShopApplyInfoView ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate, UINavigationControllerDelegate>

/* tableView */
@property (nonatomic, strong) UITableView *tableView;

/* listAry */
@property (nonatomic, strong) NSArray *listAry;

/* currentIndexPath */
@property (nonatomic, strong) NSIndexPath *currentIndexPath;

@end

static NSString *HNSH_ShopApplyInputCellID = @"HNSH_ShopApplyInputCellID";
static NSString *HNSH_ShopApplySelectCellID = @"HNSH_ShopApplySelectCellID";
static NSString *HNSH_ShopApplyUpLoadCellID = @"HNSH_ShopApplyUpLoadCellID";

@implementation HNSH_ShopApplyInfoView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        [self configUI];
    }
    return self;
}

- (void)setSubmitModel:(HNSH_ShopSubmitModel *)submitModel {
    _submitModel = submitModel;
    [self.tableView reloadData];
}

#pragma mark lazy
- (NSArray *)listAry {
    if (!_listAry) {
        _listAry = @[@{@"title":@"店铺名称：",@"des":@"请输入店面或品牌名称"},
                     @{@"title":@"社会信用代码：",@"des":@"请输入社会信用代码"},
                     @{@"title":@"上传营业/个体工商户执照",@"des":@"保证照片清晰可见"},
                     @{@"title":@"上传经营资质",@"des":@"保证照片清晰可见"},
                     @{@"title":@"上传授权书",@"des":@"保证照片清晰可见"}];
    }
    return _listAry;
}

- (void)configUI {
    
    [self addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    self.tableView.backgroundColor = [UIColor appWhiteLabelColor];
    
    [self.tableView registerClass:[HNSH_ShopApplyInputCell class] forCellReuseIdentifier:HNSH_ShopApplyInputCellID];
    [self.tableView registerClass:[HNSH_ShopApplySelectCell class] forCellReuseIdentifier:HNSH_ShopApplySelectCellID];
    [self.tableView registerClass:[HNSH_ShopApplyUpLoadCell class] forCellReuseIdentifier:HNSH_ShopApplyUpLoadCellID];
}
#pragma mark - delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.listAry.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01f;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [UIView new];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0 || indexPath.row == 1) {
        HNSH_ShopApplyInputCell *cell = [tableView dequeueReusableCellWithIdentifier:HNSH_ShopApplyInputCellID];
        NSDictionary *dict = self.listAry[indexPath.row];
        cell.title = dict[@"title"];
        cell.placeholder = dict[@"des"];
        if (self.submitModel) {
            if (indexPath.row == 0) {
                cell.textField.text = self.submitModel.name;
            } else if (indexPath.row == 1) {
                cell.textField.text = self.submitModel.register_number;
            }
        }
        WeakSelf(weakSelf);
        cell.inputBlock = ^(NSString * _Nonnull inputString) {
            if (indexPath.row == 0) {
                weakSelf.submitModel.name = inputString;
            } else if (indexPath.row == 1) {
                weakSelf.submitModel.register_number = inputString;
            }
        };
        return cell;
    } else {
        HNSH_ShopApplyUpLoadCell *cell = [tableView dequeueReusableCellWithIdentifier:HNSH_ShopApplyUpLoadCellID];
        NSDictionary *dict = self.listAry[indexPath.row];
        cell.title = dict[@"title"];
        cell.desString = dict[@"des"];
        if (indexPath.row == 2) {//营业执照
            cell.imgString = self.submitModel.license_url;
        } else if (indexPath.row == 3) {//经营资质
            cell.imgString = self.submitModel.qualification_url;
        } else if (indexPath.row == 4) {//授权书
            cell.imgString = self.submitModel.authorization_url;
        }
        WeakSelf(weakSelf);
        cell.showBlock = ^{
            if (indexPath.row == 2) {//营业执照
                [weakSelf loadConfigRuleInfoWithKey:@"shop_example_license"];
            } else if (indexPath.row == 3) {//经营资质
                [weakSelf loadConfigRuleInfoWithKey:@"shop_example_qualification"];
            } else if (indexPath.row == 4) {//授权书
                [weakSelf loadConfigRuleInfoWithKey:@"shop_example_authorization"];
            }
        };
        cell.addBlock = ^(HNSH_ShopApplyUpLoadCell * _Nonnull currentCell) {
            NSIndexPath *index = [weakSelf.tableView indexPathForCell:currentCell];
            weakSelf.currentIndexPath = index;
            [weakSelf chooseImage];
        };
        return cell;
    }
}

- (void)loadConfigRuleInfoWithKey:(NSString *)key {
    [HNSH_UserNetServer requestConfigRuleInfoWithKey:key success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            HNSH_MineImageAlert *alert = [[HNSH_MineImageAlert alloc]initWithFrame:CGRectMake(0, 0, 287, 286)];
            alert.imgString = [NSString stringWithFormat:@"%@",responseObject.resultset[@"content"]];
            [alert showView];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kNavBarAndStatusBarHeight, kScreenWidth, kScreenHeight-kNavBarAndStatusBarHeight) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.estimatedRowHeight = 44;
        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:NSStringFromClass([UITableViewCell class])];
        
    }
    return _tableView;
}

//MARK: 选择图片
- (void)chooseImage {
    UIAlertController * alertSheet = [UIAlertController alertControllerWithTitle:@"修改头像" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    [alertSheet addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [HNSH_AuthTool requestCameragraph:^(BOOL isAuth) {
            if (isAuth) {
                [self startChooseImage:UIImagePickerControllerSourceTypeCamera];
            } else {
                [self makeToast:@"未获得权限，无法上传图片"];
            }
        }];
    }]];
    [alertSheet addAction:[UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [HNSH_AuthTool requestForPhotoAuth:^(BOOL isAuth) {
            if (isAuth) {
                [self startChooseImage:UIImagePickerControllerSourceTypePhotoLibrary];
            } else {
                [self makeToast:@"未获得权限，无法上传图片"];
            }
        }];
    }]];
    [alertSheet addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [[UIViewControllerHelper findCurrentShowingViewController] presentViewController:alertSheet animated:YES completion:nil];
}

- (void)startChooseImage:(UIImagePickerControllerSourceType)sourceType{
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.allowsEditing = YES;
    imagePicker.delegate = self;
    imagePicker.sourceType = sourceType;
    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
    [[UIViewControllerHelper findCurrentShowingViewController] presentViewController:imagePicker animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate Methods
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [picker dismissViewControllerAnimated:YES completion:^{
        NSData * data = UIImageJPEGRepresentation([info objectForKey:UIImagePickerControllerEditedImage], 0.5);
        if (!data) {
            data = UIImageJPEGRepresentation([info objectForKey:UIImagePickerControllerOriginalImage], 0.5);
        }
        [self commitImgToAliyunOSS:data];
    }];
}


//MARK: 上传图片到七牛
- (void)commitImgToAliyunOSS:(NSData *)imgData{
    UIImage * image = [UIImage imageWithData:imgData];
    [ST_BaseNetManager uploadImageWithImageData:image progress:^(NSString *key, float percent) {
        
    } complate:^(NSString * _Nonnull urlString) {
        if (urlString && urlString.length) {
            if (self.currentIndexPath.row == 2) {//营业执照
                self.submitModel.license_url = urlString;
            } else if (self.currentIndexPath.row == 3) {//经营资质
                self.submitModel.qualification_url = urlString;
            } else if (self.currentIndexPath.row == 4) {//授权书
                self.submitModel.authorization_url = urlString;
            }
            [self.tableView reloadRowAtIndexPath:self.currentIndexPath withRowAnimation:UITableViewRowAnimationFade];
        }
    }];
}


@end
